package com.nmgs.util.zip;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;

import java.io.*;

public class TarUtil {
    /*
     *解压缩tar文件
     * */
    public static void unCompressTar(String srcfilePath, String destpath)
            throws IOException {
        unCompressTar(new FileInputStream(srcfilePath), destpath);
    }
    /*
     *解压缩tar文件
     * */
    public static void unCompressTar(File srcfile, String destpath)
            throws IOException {
        unCompressTar(new FileInputStream(srcfile), destpath);
    }

    /*
     *解压缩tar文件
     * */
    public static void unCompressTar(InputStream inputStream, String destPath)
            throws IOException {
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        TarArchiveInputStream taris = new TarArchiveInputStream(bis);
        TarArchiveEntry entry = null;
        while ((entry = taris.getNextTarEntry()) != null) {
            File newFile = UtilFile.newFileWithCheck(destPath,  entry.getName());
            if (entry.isDirectory()) {
                newFile.mkdirs();
            } else {
                /*
                 * 父目录不存在则创建
                 */
                File parent = newFile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int len;
                byte[] buf = new byte[1024];
                while ((len = taris.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                bos.flush();
                bos.close();
            }
        }
        taris.close();
    }
}

